package com.example.workapp;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class ScreenTrans extends AppCompatActivity {

    // ----------------------------------------
    public static void installAndLaunchApp(Context context, String packageName, String assetApkName) {
        if (isAppInstalled(context, packageName)) {
            launchApp(context, packageName);
        } else {
            installApkFromAssets(context, assetApkName, () -> launchApp(context, packageName));
        }
    }

    // **1️⃣ 检测应用是否安装**
    private static boolean isAppInstalled(Context context, String packageName) {
        try {
            context.getPackageManager().getPackageInfo(packageName, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            System.out.println(e);
            return false;
        }
    }

    // **2️⃣ 安装 APK**
    private static void installApkFromAssets(Context context, String assetApkName, Runnable callback) {
        File apkFile = new File(context.getExternalFilesDir(null), assetApkName);

        try (InputStream is = context.getAssets().open(assetApkName);
             FileOutputStream fos = new FileOutputStream(apkFile)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri apkUri = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) ?
                FileProvider.getUriForFile(context, context.getPackageName() + ".provider", apkFile) :
                Uri.fromFile(apkFile);

        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(intent);

        callback.run();  // 安装后回调
    }

    // **3️⃣ 启动已安装的应用**
    private static void launchApp(Context context, String packageName) {
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        if (launchIntent != null) {
            context.startActivity(launchIntent);
        } else {
            System.out.println("App not found!");
        }
    }
    // ----------------------------------------
    // installAndLaunchApp(context, "mirrorapp.android", "mirrorapp.apk")

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_screen_trans);
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//            return insets;
//        });
        Button to_screen_webview_btn=findViewById(R.id.screen_recv);
        to_screen_webview_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开webview active
                Intent intent = new Intent(ScreenTrans.this, WiFiActivity.class);
                intent.putExtra("flag",2);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("TARGET_DEVICE_MAC_ADDRESS","36:ea:8c:81:9e:c9");
                startActivity(intent);
                // finish();
            }
        });
        Button to_start_app_btn =findViewById(R.id.screen_sender);
        to_start_app_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                installAndLaunchApp(ScreenTrans.this, "mirrorapp.android", "mirrorapp.apk");
                Intent intent=new Intent(ScreenTrans.this, WifiClientActivity.class);
                intent.putExtra("flag",2);
                intent.putExtra("TARGET_DEVICE_MAC_ADDRESS","36:ea:8c:81:9e:c9");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }
}